package com.crm.smartmachine

import com.crm.smartmachine.api.Api
import com.crm.smartmachine.contants.Constants
import com.crm.smartmachine.repository.GlobalRepository
import com.crm.smartmachine.viewmodel.MainViewModel
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.dsl.module
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.io.IOException
import java.util.concurrent.TimeUnit

val appModule = module {

    single { createOkHttpClient() }
    single { createRetrofit(get(), Constants.BASE_URL) }
    single { createWebService<Api>(get()) }
    single { GlobalRepository(get()) }
    viewModel { MainViewModel(get(), get()) }
}

fun createOkHttpClient(): OkHttpClient {
    val baseUrlInterceptor = object : Interceptor {
        @Throws(IOException::class)
        override fun intercept(chain: Interceptor.Chain): Response { // 获取request
            val request: Request = chain.request()
            // 从request中获取原有的HttpUrl实例oldHttpUrl
            val url = Constants.BASE_URL
            var nurl = url.toHttpUrlOrNull()
            val old = request.url
            nurl?.let {
                nurl = old.newBuilder().scheme(it.scheme).host(it.host).port(it.port).build()
            }
            return if (nurl != null) {
                chain.proceed(request.newBuilder().url(nurl!!).build())
            } else {
                chain.proceed(request)
            }
        }
    }
    val mTokenInterceptor = object : Interceptor {
        @Throws(IOException::class)
        override fun intercept(chain: Interceptor.Chain): Response {
//            val token = SPUtils.getString(Constants.TOKEN)
            val authorised = chain.request().newBuilder()
//                .addHeader("clientId", "mask")
//            if (!TextUtils.isEmpty(token)) {
//                authorised.removeHeader("Authorization")
//                authorised.addHeader(
//                    "Authorization",
//                    if (token.isNullOrEmpty()) "" else "Bearer $token"
//                )
//            }
            return chain.proceed(authorised.build())
        }
    }

    val httpLoggingInterceptor = HttpLoggingInterceptor()
    httpLoggingInterceptor.level =
        if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE
    return OkHttpClient.Builder()
        .connectTimeout(60L, TimeUnit.SECONDS)
        .readTimeout(60L, TimeUnit.SECONDS)
        .addInterceptor(baseUrlInterceptor)
        .addInterceptor(httpLoggingInterceptor)
        .addNetworkInterceptor(mTokenInterceptor)
        .build()
}

fun createRetrofit(okHttpClient: OkHttpClient, url: String): Retrofit {
    return Retrofit.Builder()
        .baseUrl(url)
        .client(okHttpClient)
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) //retrofit默认支持Call返回类型，添加此行支持Observable返回类型
        .addConverterFactory(GsonConverterFactory.create())
        .build()
}

inline fun <reified T> createWebService(retrofit: Retrofit): T {
    return retrofit.create(T::class.java)
}